<template>
  <div class="">
    <header-component/>
    <h2>自定义表单Test</h2>

      <ul>
        <li v-for="item in datas" :key="item.fieldCode" :class="{'has-error':item.isError}">
          <span class="item-dt"><i v-if="isRequired(item.rules)">*</i>{{item.label}}: </span>
          <!--文本-->
          <div class="item-dd">
            <span v-if="item.type==='text'">{{formDatas[item.key]}}</span>


            <!--输入框-->
            <input v-else-if="item.type==='input'" type="text" v-model="formDatas[item.key]" @blur="verify(item)">

            <!--下拉框-->
            <select v-else-if="item.type==='select'"  v-model="formDatas[item.key]" @blur="verify(item)">
              <option v-for="option in item.options" :key="option.id" :value="option.id">{{option.value}}</option>
            </select>

            <!--单选框/复选框-->
            <div v-else-if="item.type==='radio'||item.type==='checkbox'" class="inline-block">
              <label v-for="option in item.options" :key="option.id"><input :type="item.type" :name="item.key" v-model="formDatas[item.key]" :value="option.id" @blur="verify(item)">{{option.value}}</label>
            </div>



            <!--文本域-->
            <textarea v-else-if="item.type==='textarea'" v-model="formDatas[item.key]"  @blur="verify(item)"></textarea>

            <!--联动 下拉框-->
            <!--
					  <div v-if="item.type==='selectMore'" >
						<select v-for="o,i in (formDatas[item.key].length+1)" v-model="formDatas[item.key][i]" @blur="verify(item)" @change="selectMore=changeOption(item,i,formDatas[item.key][i-1])">
						  <option v-for="option in selectMore" :value="option.id">{{option.value}}</option>
						</select>
					  </div>
			-->
            <!--地址选择-->
            <div v-else-if="item.type==='address'" class="inline-block">
              <v-distpicker  @selected="getAddress($event,item)" :province="formDatas[item.key].province" :city="formDatas[item.key].city" :area="formDatas[item.key].area"  class="inline-block"/>
              <input type="text" v-model="formDatas[item.key]['dz']" @blur="verify(item)">
            </div>

            <!--联动带输入框 下拉框-->
            <div v-else-if="item.type==='select1'" class="inline-block">
              <select v-model="formDatas[item.key][0]" @change="formDatas[item.key][1]=''">
                <option v-for="option in item.options" :key="option.id" :value="option.id">{{option.value}}</option>
              </select>
              <input type="text" v-model="formDatas[item.key][1]" @blur="verify(item)">
            </div>

            <!--提示信息-->
            <i class="iconfont icon-info" v-if="item.tips&&item.type!='upload'" :title="item.tips"></i>
            <!--错误信息-->
            <p class="msg" v-if="item.isError">{{item.msg}}</p>
          </div>
        </li>
      </ul>

      <button @click="submit">提交</button>
      <!--<input type="submit" value="提交" :disabled="disabled">-->
      <input type="button" value="取消" @click="cancel">

    <div>{{formDatas}}</div>


  </div>
</template>
<style lang="scss">
form {
  padding: 20px;
  margin: 20px 0;
  border: 1px solid #eee;
}
li {
  margin-bottom: 20px;
  font-size: 0;
}
label + label {
  margin-left: 1em;
}
.has-error .msg {
  color: red;
}
.item-dt {
  display: inline-block;
  width: 6em;
  text-align: right;
  margin-right: 20px;
  font-size: 14px;
  i {
    color: red;
    vertical-align: top;
  }
}
.item-dd {
  display: inline-block;
  font-size: 14px;
  vertical-align: top;
}
.inline-block {
  display: inline-block;
}
.icon-info {
  vertical-align: top;
  display: inline-block;
}
</style>
<script>
import AsyncValidator from "async-validator";
import VDistpicker from "v-distpicker";

export default {
  name: "Test",
  inject: ["reload"],
  components: { VDistpicker },
  data() {
    var validatezjh = (rule, value, callback) => {
      let num = value[1];

      if (num == "") {
        callback(new Error("证件号不能为空！"));
      } else {
        if (!/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num.toUpperCase())) {
          //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
          callback(new Error("身份证号长度不正确或不符合规定！"));
        } else {
          callback();
        }
      }
    };
    var validateAddress = (rule, value, callback) => {
      if (value.dz == undefined) {
        callback(new Error("请填写地址！"));
      } else {
        callback();
      }
    };
    return {
      test: [],
      datas: [
        {
          key: "xh",
          label: "学号",
          type: "text"
        },
        {
          key: "name",
          label: "姓名",
          type: "input",
          tips: "长度在 3 到 5 个字符",
          rules: [
            { required: true, message: "请输入姓名" },
            { min: 3, max: 5, message: "长度在 3 到 5 个字符" }
          ]
        },
        {
          key: "sex",
          label: "性别",
          type: "radio",
          options: [{ id: "0", value: "男" }, { id: "1", value: "女" }],
          rules: [{ required: true, message: "请选择性别" }]
        },
        {
          key: "hobby",
          label: "爱好",
          type: "checkbox",
          options: [
            { id: "0", value: "唱歌" },
            { id: "1", value: "跳舞" },
            { id: "2", value: "画画" },
            { id: "3", value: "游泳" }
          ],
          tips: "最多只能选择2个",
          rules: [
            { required: true, message: "爱好不能为空" },
            { type: "array", max: 2, message: "最多只能选择2个" }
          ]
        },
        {
          key: "hkxz",
          label: "户口性质",
          type: "select",
          options: [{ id: "cz", value: "城镇" }, { id: "xc", value: "乡村" }],
          rules: [{ required: true, message: "请选择户口性质" }]
        },
        {
          key: "zjh",
          label: "证件号",
          type: "select1",
          options: [
            { id: "sfz", value: "身份证" },
            { id: "xsz", value: "学生证" },
            { id: "jsz", value: "教师证" }
          ],
          rules: [
            { required: true, message: "请填写证件号" },
            { validator: validatezjh }
          ]
        },
        {
          key: "address1",
          label: "户籍地址",
          type: "address",
          rules: [{ required: true, validator: validateAddress }]
        },
        {
          key: "address",
          label: "住址",
          type: "address",
          rules: [{ required: true, validator: validateAddress }]
        },
        {
          key: "phone",
          label: "电话号码",
          type: "input",
          rules: [
            /*{ required: true, message: '请输入电话号码' },*/
            { pattern: "/^1[34578]d{9}$/", message: "您的手机号码输入错误" }
          ]
        },
        {
          key: "email",
          label: "邮箱",
          type: "input",
          rules: [
            { required: false, type: "email", message: "您的邮箱输入错误" }
          ]
        },
        {
          key: "introduce",
          label: "自我简述",
          type: "textarea",
          tips: "长度在 3 到 15 个字符",
          rules: [{ min: 3, max: 15, message: "长度在 3 到 15 个字符" }]
        }
      ],
      formDatas: {
        xh: "3920332308", //默认值
        name: "aaa",
        hkxz: "cz",
        hobby: [], //复选框必须定义成数组
        address: {},
        address1: {
          province: 440000,
          city: "广州市",
          area: "海珠区",
          dz: "文一西路2122号"
        },
        sr: "2018-10-18",
        zjh: []
      },
      selectMore: {},
      disabled: false
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      console.log(URL.createObjectURL(file.raw));
    },
    beforeAvatarUpload(file) {
      //consol.log(item.limit);
      const isLt2M = file.size / 1024 / 1024 < 0.1;

      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },

    getAddress(data, item) {
      this.formDatas[item.key]["province"] = data.province.value;
      this.formDatas[item.key]["city"] = data.city.value;
      this.formDatas[item.key]["area"] = data.area.value;
    },
    /*getOption(item,i){
        console.log(i);
        if(i==0){
          console.log('a');
          return item.options;
        }else{
          console.log('b');
          return this.selectMore;
        }
      },
      changeOption(item,i,id){
        console.log(i)
        if(i==0){

          console.log(item.options);
          return item.options;
        }else{
          item.options.forEach(function(o){
            if(o.id==id){
              console.log('1-id:'+o.id)
              console.log(o);
              return o.options;
            }
          })
        }
      },*/

    //提交
    submit() {
      let hasError;
      this.datas.forEach(item => {
        if (item.type != "text") {
          this.verify(item);
          hasError = item.isError || hasError;
        }
      });
      if (!hasError) {
        this.$my_message("提交成功！", "success");
        console.log(JSON.stringify(this.formDatas));
      } else {
        this.$my_message("表单还有问题，不能提交!", "error");
      }
    },
    //取消
    cancel() {
      this.reload();
      console.log("111");
    },

    //是否必填
    isRequired(rules) {
      let isRequired = false;
      if (rules && rules.length) {
        rules.every(rule => {
          if (rule.required) {
            isRequired = true;
            return false;
          }
          return true;
        });
      }
      return isRequired;
    },

    //验证
    verify(item) {
      const descriptor = {};
      descriptor[item.key] = item.rules;

      const validator = new AsyncValidator(descriptor);
      const model = {};

      model[item.key] = this.formDatas[item.key];

      validator.validate(model, { firstFields: true }, errors => {
        let isE = errors ? true : false;
        let validateMessage = errors ? errors[0].message : "";
        if (typeof item.isError == "undefined") {
          this.$set(item, "isError", isE);
        } else {
          item.isError = isE;
        }
        this.disabled = isE;
        if (typeof item.msg == "undefined") {
          this.$set(item, "msg", validateMessage);
        } else {
          item.msg = validateMessage;
        }
      });
    }
  }
};
</script>
